//
//  PhotoSelectorController.swift
//  imagePicker
//
//  Created by lzing on 16/4/5.
//  Copyright © 2016年 LZING. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"

class PhotoSelectorController: UICollectionViewController {
    
    /// 保存选中的图片
    var photos : [UIImage] = [UIImage]()
    // 最大图片数
    private let MaxCount = 6
    // 记录点击cell的indexPath
    var clickIndexPath : NSIndexPath?
    
    private let layout = UICollectionViewFlowLayout()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Register cell classes
        self.collectionView!.registerClass(PhotoSelectorCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        // 设置collectionView
        setupCollectionView()
    }
    /// 设置collectionView
    private func setupCollectionView() {
        collectionView?.backgroundColor = UIColor.whiteColor()
        layout.itemSize = CGSize(width: 80, height: 80)
        // 内边距
        collectionView?.contentInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
    }

    init() {
        super.init(collectionViewLayout: layout)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // MARK: UICollectionViewDataSource
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        //  当图片数量小于最大张数时,cell的数量 = 图片数量 + 1
        //  当图片数量等于最大张数时,cell的数量 = 图片数量
        return photos.count < MaxCount ? photos.count + 1 : photos.count
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! PhotoSelectorCell
    
        cell.backgroundColor = UIColor.brownColor()
        
        if indexPath.item < photos.count {
            // 有图片
            cell.image = photos[indexPath.item]
        } else {
            // 设置加号按钮,防止复用
            cell.setupAddButton()
        }
        cell.delegate = self
        return cell
    }
}

//MARK: - <PhotoSelectorCellDelegate>
extension PhotoSelectorController : PhotoSelectorCellDelegate {
    ///  加号按钮点击事件
    func photoSelectorCellDidClickAddButton(cell: PhotoSelectorCell) {
        // 图片选择器
        let picker = UIImagePickerController()
        picker.delegate = self
        clickIndexPath = collectionView?.indexPathForCell(cell)
        //弹出
        presentViewController(picker, animated: true, completion: nil)
    }
    ///  删除按钮点击事件
    func photoSelectorCellDidClickDeleteButton(cell: PhotoSelectorCell) {
        // 点击的cell
        let indexPath = collectionView?.indexPathForCell(cell)
        // 再找到照片
        photos.removeAtIndex(indexPath!.item)
        collectionView?.reloadData()
    }
}

//MARK: - <UIImagePickerControllerDelegate,UINavigationControllerDelegate>
extension PhotoSelectorController : UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    // 选中照片调用
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        let newImage = image.scaleImage()
        // 如果点击的是加号就添加图片,如果点击的是图片就修改图片
        if clickIndexPath?.item == photos.count {
            // 点击加号按钮
            photos.append(newImage)
        } else {
            // 之前点击的是图片,修改图片
            photos[clickIndexPath!.item] = image
        }
        collectionView?.reloadData()
        // dismiss
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
}

//MARK: - 定义协议
protocol PhotoSelectorCellDelegate : NSObjectProtocol {
    // 定义方法
    ///  点击增加按钮
    func photoSelectorCellDidClickAddButton(cell : PhotoSelectorCell)
    ///  点击删除按钮
    func photoSelectorCellDidClickDeleteButton(cell : PhotoSelectorCell)
}

//MARK: - 自定义cell
class PhotoSelectorCell: UICollectionViewCell {
    //MARK: - attribute
    var image : UIImage? {
        didSet {
            // 设置按钮图片
            addButton.setImage(image, forState: UIControlState.Normal)
            // 显示删除按钮
            deleteButton.hidden = false
        }
    }
    // 定义代理属性
    weak var delegate : PhotoSelectorCellDelegate?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        ///  添加子控件
        addSubview()
        ///  添加约束
        addConstraint()
    }
    
    ///  设置加号按钮
    func setupAddButton() {
        // 设置图片
        addButton.setImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
        // 隐藏删除按钮
        deleteButton.hidden = true
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    ///  添加子控件
    private func addSubview() {
        contentView.addSubview(addButton)
        contentView.addSubview(deleteButton)
    }
    ///  添加约束
    private func addConstraint() {
        addButton.translatesAutoresizingMaskIntoConstraints = false
        deleteButton.translatesAutoresizingMaskIntoConstraints = false
        // 加号按钮约束
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[addButton]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["addButton" : addButton]))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[addButton]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["addButton" : addButton]))
        // 删除按钮约束
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[deleteButton]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["deleteButton" : deleteButton]))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[deleteButton]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["deleteButton" : deleteButton]))
    }
    ///  添加按钮点击事件
    @objc private func addButtonDidClick() {
        delegate?.photoSelectorCellDidClickAddButton(self)
    }
    /// 删除按钮点击事件
    @objc private func deleteButtonDidClick() {
        delegate?.photoSelectorCellDidClickDeleteButton(self)
    }
    
    //MARK: - lazy
    /// 加号按钮
    private lazy var addButton : UIButton = {
        let addButton = UIButton()
        addButton.setImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
        addButton.addTarget(self, action: "addButtonDidClick", forControlEvents: UIControlEvents.TouchUpInside)
        // 设置图片的填充模型
        addButton.imageView?.contentMode = UIViewContentMode.ScaleAspectFill
        return addButton
    }()
    /// 删除按钮
    private lazy var deleteButton : UIButton = {
        let deleteButton = UIButton()
        deleteButton.setImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
        deleteButton.addTarget(self, action: "deleteButtonDidClick", forControlEvents: UIControlEvents.TouchUpInside)
        return deleteButton
    }()
}
